<script lang="ts" setup>
import { useAdminAuthenticationStore } from '../store/adminAuthentication'
import { get, post } from '@/utils/api'
import { storeToRefs } from 'pinia'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { rules } from '../attribute/rules'
import { MessagePlugin } from 'tdesign-vue-next'
import { useCurrentDate } from '@/utils/currentDate'

const store = useAdminAuthenticationStore()
const { saveDialogVisible, saveMode, isForever } = storeToRefs(store)
const { getData, formData, appNameModel } = store

const requestUrl = computed(() => {
  return saveMode.value === 'add' ? '/api/auth/insert' : '/api/auth/update'
})
const header = computed(() => {
  return saveMode.value === 'add' ? '添加授权' : '编辑授权'
})
const closeDialog = () => {
  saveDialogVisible.value = false
  resetFormData()
}
const formRef = ref<any>(null)

const resetFormData = () => {
  formRef.value.reset({ type: 'initial' })
}

const confirmLoading = ref(false)

const submit = async () => {
  const result = await formRef.value.validate()
  if (result === true) {
    confirmLoading.value = true
    const response = await post(requestUrl.value, formData)
    confirmLoading.value = false
    MessagePlugin(response.status, response.message)
    if (response.status === 'success') {
      closeDialog()
      await getData()
    }
  }
}

const appNameOptions = ref<object[]>()

const getAppNameLists = async () => {
  const data = await get('/api/program/getLists')
  appNameOptions.value = data.map((item: any) => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
onMounted(() => {
  getAppNameLists()
})

const selectChange = (app: any) => {
  formData.appId = app.value.toString()
  formData.appName = app.label
}

const typeOptions = reactive([
  {
    label: '域名',
    value: 0
  },
  {
    label: 'IP',
    value: 1
  }
])

watch(
  () => isForever.value,
  () => {
    const currentDate = useCurrentDate()
    if (isForever.value) {
      formData.overDate = '2099-12-31'
    } else {
      formData.overDate = currentDate
    }
  }
)
</script>

<template>
  <t-dialog
    :visible="saveDialogVisible"
    @close="closeDialog"
    :header="header"
    @confirm="submit"
    :confirm-btn="{ loading: confirmLoading }"
  >
    <t-row style="padding: 10px">
      <t-form
        ref="formRef"
        :data="formData"
        :rules="rules"
        :label-width="70"
        label-align="left"
        style="width: 100%"
      >
        <t-form-item label="应用名称" name="appName">
          <t-select
            :options="appNameOptions"
            value-type="object"
            v-model="appNameModel"
            @change="selectChange"
            placeholder="请选择应用"
          />
        </t-form-item>

        <t-form-item label="应用ID" name="appId">
          <t-input v-model="formData.appId" placeholder="应用ID（自动填入）" readonly />
        </t-form-item>

        <t-form-item label="验证方式" name="appId">
          <t-select v-model="formData.type" :options="typeOptions" />
        </t-form-item>

        <t-form-item label="授权主体" name="domain">
          <t-input placeholder="请输入授权域名或IP" v-model="formData.domain" />
        </t-form-item>

        <t-form-item label="用户ID" name="userId">
          <t-input v-model="formData.userId" placeholder="请输入用户ID" />
        </t-form-item>

        <t-form-item label="授权状态">
          <t-switch v-model="formData.status" :custom-value="[1, 0]" />
        </t-form-item>

        <t-form-item label="永久授权">
          <t-switch v-model="isForever" />
        </t-form-item>

        <t-form-item v-show="!isForever" label="过期时间" name="overDate">
          <t-date-picker v-model="formData.overDate" placeholder="请选择过期时间" />
        </t-form-item>
      </t-form>
    </t-row>
  </t-dialog>
</template>
